package com.fxu.tpl.rest;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fxu.framework.biz.rest.ApiBizRest;
import com.fxu.framework.core.base.Constant;
import com.fxu.framework.core.base.Result;
import com.fxu.framework.core.holder.RequestHolder;
import com.fxu.framework.core.service.impl.ApiServiceImpl;
import com.fxu.framework.core.sql.SCascade;
import com.fxu.framework.core.sql.SQuery;
import com.fxu.framework.core.sql.SUtils;
import com.fxu.gen.*;
import com.fxu.gen.cloud.RestImpl;
import com.fxu.gen.cloud.Service;
import com.fxu.gen.cloud.ServiceImpl;
import com.fxu.gen.enums.ClnType;
import com.fxu.gen.enums.TplEnum;
import com.fxu.role.entity.Admin;
import com.fxu.role.entity.AdminRole;
import com.fxu.role.entity.Role;
import com.fxu.tpl.entity.*;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.Valid;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/***
 * <p>learned</p>
 * 表：[table]的业务逻辑接口实现
 * @author fangxu
 * @version 2019-09-23
 ***/
@Component
@RequiredArgsConstructor
public class TableRestImpl implements ApiBizRest<Table> {
	private final static Logger logger = LoggerFactory.getLogger(TableRestImpl.class);
	private final ApiServiceImpl apiRestImpl;
/*=== 自动生成代码 开始 ===*/
/*=== 自动生成代码 结束 ===*/
	@Override
	public void fillBeans(List<Table> beans, List<String> showFlags) {
		if (showFlags.contains("linkList.table")) {
			Set<Long> ids = beans.stream().map(Table::getLinkList).filter(Objects::nonNull).flatMap(Collection::stream)
					.map(Link::getLinkTableId).collect(Collectors.toSet());
			List<Table> roleList = apiRestImpl.listBy(SUtils.query(Table.class).show(Table::getId, Table::getName).in(Table::getId, ids));
			for (Table bean : beans) {
				for (Link link : bean.getLinkList()) {
					if (link.getLinkTableId() != null) {
						link.setLinkTable(CollUtil.findOne(roleList, v -> v.getId().equals(link.getLinkTableId())));
					}
				}
			}
		}
	}
	private final Column ID_CLN = Column.builder().name(Constant.ID_NAME).cmmt("UUID").type(1).formType(1).notNull(true).length(32).unsigned(false).required(false).listShow(true).queryType(1).overflow(true).formShow(false).listWidth(70).build();
	private final Column ID_CLN_AUTO = Column.builder().name(Constant.ID_NAME).cmmt("自增ID").type(4).formType(1).notNull(true).length(8).unsigned(true).required(false).listShow(true).queryType(1).overflow(true).formShow(false).listWidth(70).build();
	private final Column STATUS_CLN = Column.builder().name(Constant.CLN_STATUS).cmmt("状态").defVal("1").limits("1:正常,0:删除").type(3).formType(5).notNull(true).length(4).unsigned(true).required(false).listShow(true).queryType(1).formShow(false).listWidth(70).build();
	private final Column VERSION_CLN = Column.builder().name(Constant.CLN_VERSION).cmmt("版本号").defVal("1").type(3).formType(5).notNull(true).length(8).unsigned(true).required(false).listShow(false).formShow(false).build();
	private final Column CREATE_BY_CLN = Column.builder().name(Constant.CLN_CREATE_BY).cmmt("创建者").defVal("空").type(1).formType(1).notNull(false).length(64).unsigned(false).required(false).listShow(false).formShow(false).build();
	private final Column CREATE_TIME_CLN = Column.builder().name(Constant.CLN_CREATE_TIME).cmmt("创建时间").defVal("NOW").type(8).formType(3).notNull(false).length(0).unsigned(false).required(false).listShow(true).formShow(false).build();
	private final Column UPDATE_BY_CLN = Column.builder().name(Constant.CLN_MODIFY_BY).cmmt("修改者").defVal("空").type(1).formType(1).notNull(false).length(64).unsigned(false).required(false).listShow(false).formShow(false).build();
	private final Column UPDATE_TIME_CLN = Column.builder().name(Constant.CLN_MODIFY_TIME).cmmt("修改时间").defVal("NOW").type(8).formType(3).notNull(false).length(0).unsigned(false).required(false).listShow(false).formShow(false).build();
	@Override
	public Result<Table> saveBefore(Table oldBean, Table bean) {
		if (oldBean == null) { // 添加
			if (bean.getColumnList() == null) {
				return Result.error("字段列表不能为空!");
			}
			if (bean.getRowCol() == null) {
				bean.setRowCol(2);
			}
			Long projectId = bean.getProjectId();
			if (projectId == null || projectId <= 0) {
				return Result.error("请选择好项目!");
			}
			List<Column> newList = new ArrayList<>();

			// 加入其他字段
			Column statusColumn = STATUS_CLN;
			for (int i = 0, size = bean.getColumnList().size(); i < size; i++) {
				Column column = bean.getColumnList().get(i);
				if (i == 0) {
					boolean isLong = column.getType().intValue() == ClnType.LONG.code();
					// 最先加入ID字段
					newList.add(isLong ? setSpecial(ID_CLN_AUTO) : setSpecial(ID_CLN));
					// 定制ID
					newList.get(0).setName(bean.getColumnList().get(0).getName());
				}
				// 排除特殊字段
				else if (!isSpecial(i, column.getName())) {
					newList.add(column);
				} else if (Constant.CLN_STATUS.equals(column.getName()) && !StrUtil.isEmpty(column.getLimits())) {
					statusColumn.setType(column.getType());
					statusColumn.setLength(column.getLength());
					statusColumn.setLimits(column.getLimits());
					statusColumn.setUnsigned(column.getUnsigned());
					if (StrUtil.isEmpty(column.getLimits()) || !column.getLimits().contains(":")) {
						return Result.error("status的限制必须填写完整!");
					}
					if (column.getLimits().equals("1:隐藏,0:删除,2:显示")) {
						statusColumn.setDefVal("2");
					} else {
						statusColumn.setDefVal(column.getLimits().substring(0, column.getLimits().indexOf(":")));
					}
				}
			}
			if (bean.isHasCreateBy()) {
				newList.add(setSpecial(CREATE_BY_CLN));
			}
			if (bean.isHasUpdateBy()) {
				newList.add(setSpecial(UPDATE_BY_CLN));
			}
			newList.add(setSpecial(CREATE_TIME_CLN));
			if (bean.isHasUpdateTime()) {
				newList.add(setSpecial(UPDATE_TIME_CLN));
			}
			if (bean.isHasStatus()) {
				newList.add(setSpecial(statusColumn));
			}
			if (bean.isHasVersion()) {
				newList.add(setSpecial(VERSION_CLN));
			}

			bean.setColumnList(newList);

		} else { // 编辑
			if (bean.getColumnList() != null) {
				boolean hasStatus = AutoUtil.hasColumn(bean.getColumnList(), Constant.CLN_STATUS);
				boolean hasVersion = AutoUtil.hasColumn(bean.getColumnList(), Constant.CLN_VERSION);
				boolean hasCreateBy = AutoUtil.hasColumn(bean.getColumnList(), Constant.CLN_CREATE_BY);
				boolean hasModifyBy = AutoUtil.hasColumn(bean.getColumnList(), Constant.CLN_MODIFY_BY);
				boolean hasCreateTime = AutoUtil.hasColumn(bean.getColumnList(), Constant.CLN_CREATE_TIME);
				boolean hasModifyTime = AutoUtil.hasColumn(bean.getColumnList(), Constant.CLN_MODIFY_TIME);
				// 表不能改项目
				List<Column> newList = new ArrayList<>();
				for (Column column : bean.getColumnList()) {
					if (Constant.CLN_CREATE_TIME.equals(column.getName())) {
						if (bean.isHasCreateBy() && !hasCreateBy) {
							newList.add(setSpecial(CREATE_BY_CLN));
						}
						if (bean.isHasUpdateBy() && !hasModifyBy) {
							newList.add(setSpecial(UPDATE_BY_CLN));
						}
						if (!hasCreateTime) {
							newList.add(setSpecial(CREATE_TIME_CLN));
						}
						if (bean.isHasUpdateTime() && !hasModifyTime) {
							newList.add(setSpecial(UPDATE_TIME_CLN));
						}
					}
					newList.add(column);
					if (Constant.CLN_CREATE_TIME.equals(column.getName())) {
						if (bean.isHasUpdateTime() && !hasModifyTime) {
							newList.add(setSpecial(UPDATE_TIME_CLN));
						}
						if (bean.isHasStatus() && !hasStatus) {
							Column statusColumn = setSpecial(STATUS_CLN);
							if (column.getLimits() != null && column.getLimits().contains(":")) {
								statusColumn.setDefVal(column.getLimits().substring(0, column.getLimits().indexOf(":")));
								if (column.getLimits().equals("1:隐藏,0:删除,2:显示")) {
									statusColumn.setDefVal("2");
								}
							}
							newList.add(statusColumn);
						}
						if (bean.isHasVersion() && !hasVersion) {
							newList.add(setSpecial(VERSION_CLN));
						}
					}
				}
				if (!hasCreateTime) {
					if (bean.isHasCreateBy() && !hasCreateBy) {
						newList.add(setSpecial(CREATE_BY_CLN));
					}
					if (bean.isHasUpdateBy() && !hasModifyBy) {
						newList.add(setSpecial(UPDATE_BY_CLN));
					}
					newList.add(setSpecial(CREATE_TIME_CLN));
					if (bean.isHasUpdateTime() && !hasModifyTime) {
						newList.add(setSpecial(UPDATE_TIME_CLN));
					}
					if (bean.isHasUpdateTime() && !hasModifyTime) {
						newList.add(setSpecial(UPDATE_TIME_CLN));
					}
					if (bean.isHasStatus() && !hasStatus) {
						newList.add(setSpecial(STATUS_CLN));
					}
					if (bean.isHasVersion() && !hasVersion) {
						newList.add(setSpecial(VERSION_CLN));
					}
				}
				bean.setColumnList(newList);
			}
			if (bean.getStatus() != null && oldBean.getStatus() != null && !bean.getStatus().equals(oldBean.getStatus())) {
				if (bean.getStatus() == 0) {
					oldBean.setProject(apiRestImpl.findById(Project.class, oldBean.getProjectId()));
					oldBean.setModule(apiRestImpl.findById(Module.class, oldBean.getModuleId()));
					List<TplEnum> tplEnums = getTplFileEnumList(oldBean);
					for (TplEnum tfe : tplEnums) {
						File file = getNewFile(oldBean, tfe);
						if (file != null && file.exists() && file.isFile()) {
							logger.info("删除文件:" + file);
							file.delete();
						}
					}
				}
			}
			if (bean.getColumnList() != null) {
				for (Column column : bean.getColumnList()) {
					if (column.isDecimal() && (column.getDotRight() == null)) {
						return Result.error("Decimal字段必须填写逗号后几位!");
					}
					if (column.isDecimal() && column.getDotRight() > column.getLength()) {
						return Result.error("Decimal字段逗号后几位必须小于字段长度!");
					}
				}
			}
		}

		if (bean.getColumnList() != null) {
			int orderNo = 1;
			for (Column column : bean.getColumnList()) {
				column.setOrderNo(orderNo++);
			}
			// 设置显示字段
			String showCln = bean.getColumnList().get(0).getName();
			List<String> clns = CollUtil.toList("name", "no", "note_no", "code", "title");
			List<String> clnNames = bean.getColumnList().stream().map(Column::getName).filter(clns::contains).collect(Collectors.toList());
			if (clnNames.contains("name")) {
				showCln = "name";
			} else if (clnNames.contains("code")) {
				showCln = "code";
			} else if (clnNames.contains("no")) {
				showCln = "no";
			} else if (clnNames.contains("note_no")) {
				showCln = "noteNo";
			} else if (clnNames.contains("title")) {
				showCln = "title";
			}
			bean.setShowCln(showCln);
		}
		// 如果删除了级联则为空
		System.out.println("bean.getLinkList()=" + bean.getLinkList());
		return Result.ok(bean);
	}
	
	private Column setSpecial(Column column) {
		column.setId(null);
		column.setTableId(0L);
    	return column;
    }
	private boolean isSpecial(int i, String name) {
		return i == 0 || Constant.ID_NAME.equals(name) || Constant.CLN_STATUS.equals(name) || Constant.CLN_VERSION.equals(name)
				|| Constant.CLN_CREATE_BY.equals(name) || Constant.CLN_CREATE_TIME.equals(name)
				|| Constant.CLN_MODIFY_BY.equals(name) || Constant.CLN_MODIFY_TIME.equals(name);
    }

	public Result<String> autoGen(@Valid List<String> ids) {
		Assert.notEmpty(ids);
		Table table;
		List<TplEnum> tplEnums;
		for (String id : ids) {
			table = getTable(id);
			if (table == null) {
				continue;
			}
			tplEnums = getTplFileEnumList(table);
			for (TplEnum tfe : tplEnums) {
				saveFile(table, tfe);
			}
		}
		return Result.ok("自动生成成功!");
	}
	
	public List<TplEnum> getTplFileEnumList(Table table) {
		List<TplEnum> tplEnums = CollUtil.toList(TplEnum.Entity, TplEnum.Mapper);
		if (table.getGenFiles() != null) {
			if (table.getGenFiles().contains("pageReq")) {
				tplEnums.add(TplEnum.PageReq);
			}
			if (table.getGenFiles().contains("restImpl")) {
				tplEnums.add(TplEnum.RestImpl);
			}
			if (table.getGenFiles().contains("controller")) {
				tplEnums.add(TplEnum.Controller);
			}
			if (table.getGenFiles().contains("service")) {
				tplEnums.add(TplEnum.Service);
				tplEnums.add(TplEnum.ServiceImpl);
			}
			if (table.getGenFiles().contains("vue")) {
				tplEnums.add(TplEnum.VueHtml);
			}
			if (table.getGenFiles().contains("vben")) {
				tplEnums.add(TplEnum.VbenAdmin);
			}
		}
		return tplEnums;
	}
	
	private String getSavePath(Table table, TplEnum tplEnum) {
		Project project = table.getProject();
		if (tplEnum == TplEnum.VueHtml || tplEnum == TplEnum.VbenAdmin || tplEnum == TplEnum.VbenVue3) {
			return project.getVuePath();
		}
		return project.getDstPath() + table.getModule().getFolder() + "/"
				+ tplEnum.getSrcPath(project.getDstProject(), table.getModule().getName());
	}
	
	public File getNewFile(Table table, TplEnum tplEnum) {
		String newPath = getSavePath(table, tplEnum);
		String newName = tplEnum.getName(AutoUtil.getBean(table.getName()));
		return new File(newPath + newName);
	}
	
	//第三步根据模板生成新表所有代码
	private void saveFile(Table table, TplEnum tplEnum) {
		File newFile = getNewFile(table, tplEnum);
		Base base = getBase(table, tplEnum, newFile);
		if (base != null) {
			String fileTxt = base.doReplace();
			//System.out.println(fileTxt);
			if (newFile.exists()) {
				System.out.println("修改文件:" + newFile);
			} else {
				System.out.println("新生成文件:" + newFile);
			}
			FileUtil.writeUtf8String(fileTxt, newFile);
		}
	}

	//TODO 增加DTO => Base 重复
	private Base getBase(Table table, TplEnum tplEnum, File destFile) {
		switch (tplEnum) {
			case Entity:
				return new Entity(table, destFile);
//			case Feign:
//				return new Feign(table, destFile);
//			case FeignFallback:
//				return new FeignFallback(table, destFile);
			case Mapper:
				return new Mapper(table, destFile);
			case PageReq:
				return new PageReq(table, destFile);
//			case MapperXml:
//				return new MapperXml(table, destFile);
			case Service:
				return new Service(table, destFile);
			case ServiceImpl:
				return new ServiceImpl(table, destFile);
			case RestImpl:
				return new RestImpl(table, destFile);
//			case RestService:
//				return new RestService(table, destFile);
//			case RestServiceImpl:
//				return new RestServiceImpl(table, destFile);
			case Controller:
				return new Controller(table, destFile);
			case VueHtml:
				// table.getProject().getVueTpl()
				return new VueHtml(table, null);
			case VbenAdmin:
				return new VbenAdmin(table, null);
			case VbenVue3:
				return new VbenVue3(table, null);
			default:
				break;
		}
		return null;
	}

	private Table getTableByMap(Map<Long, Table> tableMap, Long tableId, List<Module> moduleList, boolean isColumn) {
		if (!tableMap.containsKey(tableId)) {
			Table table = apiRestImpl.findById(Table.class, tableId);
			if (table != null && isColumn) {
				table.setColumnList(apiRestImpl.listBy(SUtils.query(Column.class).eq(Column::getTableId, table.getId())
						.orderAsc(Column::getOrderNo).orderAsc(Column::getId)));
			}
			if (table != null) {
				table.setModule(CollUtil.findOne(moduleList, m -> m.getId().equals(table.getModuleId())));
			}
			tableMap.put(tableId, table);
		}
		return tableMap.get(tableId);
	}
	
	public Table getTable(String id) {
		Table table = apiRestImpl.findLast(SUtils.query(Table.class).id(id)
				.cascade(Table::getProject, SUtils.cascade(Project.class))
				.cascade(Table::getColumnList, SUtils.cascade(Column.class).orderAsc(Column::getOrderNo).orderAsc(Column::getId))
				.cascade(Table::getIndexList, SUtils.cascade(Index.class))
				.cascade(Table::getLinkList, SUtils.cascade(Index.class))
		);
		List<Module> moduleList = apiRestImpl.listBy(SUtils.query(Module.class)
				.eq(Module::getProjectId, table.getProjectId())
				.show(Module::getId).show(Module::getName).show(Module::getFolder)
		);
		table.setModule(CollUtil.findOne(moduleList, m -> m.getId().equals(table.getModuleId())));
		Map<Long, Table> tableMap = new HashMap<>();

		if (table.getColumnList() != null) {
			table.getColumnList().stream().filter(cln -> cln.getLinkTableId() != null && cln.getLinkTableId() > 0)
					.forEach(cln -> cln.setLinkTable(getTableByMap(tableMap, cln.getLinkTableId(), moduleList, false)));
		}

		if (table.getLinkList() != null) {
			for (Link link : table.getLinkList()) {
				if (link.getLinkTableId() != null && link.getLinkTableId() > 0) {
					//link.setLinkTable(apiRestImpl.findById(Table.class, link.getLinkTableId()));
					link.setLinkTable(getTableByMap(tableMap, link.getLinkTableId(), moduleList, true));
					// 增加子集字段链接表字段
					if (link.getLinkTable().getColumnList() != null) {
						link.getLinkTable().getColumnList().stream().filter(cln -> cln.getLinkTableId() != null && cln.getLinkTableId() > 0)
								.forEach(cln -> cln.setLinkTable(getTableByMap(tableMap, cln.getLinkTableId(), moduleList, false)));
					}
				}
				if (link.getLinkColumnId() != null && link.getLinkColumnId() > 0) {
					link.setLinkColumn(apiRestImpl.findById(Column.class, link.getLinkColumnId()));
				}
			}
		}
		return table;
	}

	public Result<String> createSql(@Valid List<String> ids) {
		Assert.notEmpty(ids, "ids不能为空!");
		StringBuilder buffer = new StringBuilder();
		for (String id : ids) {
			Table table = apiRestImpl.findLast(SUtils.query(Table.class).id(id)
					.cascade(Table::getProject, SUtils.cascade(Project.class))
					.cascade(Table::getColumnList, SUtils.cascade(Column.class).orderAsc(Column::getOrderNo).orderAsc(Column::getId))
					.cascade(Table::getIndexList, SUtils.cascade(Index.class))
			);
			if (table == null) {
				return Result.error("id=["+id+"]找不到对象!");
			}
			MySQL mysql = new MySQL(table, null);
			buffer.append("-- drop table if exists `").append(table.getName()).append("`;\n");
			buffer.append(mysql.doReplace()).append("\n");
		}
		return Result.ok(buffer.toString());
	}

	public Result<String> vbenSchemas(@Valid List<String> ids) {
		Assert.notEmpty(ids, "ids不能为空!");
		StringBuilder buffer = new StringBuilder();
		for (String id : ids) {
			Table table = getTable(id);
			if (table == null) {
				return Result.error("id=["+id+"]找不到对象!");
			}
			String module = "", tableName = table.getName();
			if (table.getModule() != null && StrUtil.isNotEmpty(table.getModule().getName())) {
				module = table.getModule().getName();
			}
			if (StrUtil.isNotEmpty(module) && table.getName().startsWith(module + "_")) {
				tableName = table.getName().substring(module.length() + 1);
			}
			buffer.append("// ").append(table.getCmmt()).append("字段\n");
			buffer.append("export const ").append(AutoUtil.firstLowerBean(tableName))
					.append("Schemas: CrudSchema[] = [\n")
					.append(VbenAdmin.getCrudSchemas(table, table.getColumnList(), 0)).append("\n]\n\n");
		}
		return Result.ok(buffer.toString());
	}

	public Result<String> modifySql(@Valid List<String> ids) {
		Assert.notEmpty(ids, "ids不能为空!");
		StringBuilder buffer = new StringBuilder();
		for (String id : ids) {
			Table table = apiRestImpl.findById(Table.class, id);
			if (table == null) {
				return Result.error("id=["+id+"]找不到对象!");
			}
			TableLog tableLog = apiRestImpl.findLast(SUtils.query(TableLog.class).eq(TableLog::getTableId, table.getId())
					.show(TableLog::getId).show(TableLog::getTableJson).show(TableLog::getSqlStr)
					.show(TableLog::getTableVersion));
			// 如果日志版本 大于等于 表结构版本, 直接返回SQL执行语句, 因为没有改动
			if (tableLog != null && tableLog.getTableVersion() >= table.getVersion()) {
				return Result.ok(tableLog.getSqlStr());
			}
			Project project = apiRestImpl.findLast(SUtils.query(Project.class).eq(Project::getId, table.getProjectId())
					.show(Project::getName));
			table.setProjectName(project.getName());
			table.setColumnList(apiRestImpl.listBy(SUtils.query(Column.class).eq(Column::getTableId, table.getId())
					.orderAsc(Column::getOrderNo).orderAsc(Column::getId)));
			table.setIndexList(apiRestImpl.listBy(SUtils.query(Index.class).eq(Index::getTableId, table.getId())));

			MySQL mysql = new MySQL(table, null);
			if (tableLog == null) {
				buffer.append("-- drop table if exists `").append(table.getName()).append("`;\n");
				buffer.append(mysql.doReplace()).append("\n");
			} else {
				Table oldTable = JSONUtil.toBean(tableLog.getTableJson(), Table.class);
				buffer.append(mysql.getAlter(oldTable)).append("\n");
			}

			tableLog = new TableLog();
			tableLog.setProjectId(table.getProjectId());
			tableLog.setTableId(table.getId());
			tableLog.setRequestIp(RequestHolder.getRequestIp());
			tableLog.setTableJson(JSONUtil.toJsonStr(table));
			tableLog.setSqlStr(buffer.toString());
			tableLog.setTableVersion(table.getVersion());
			apiRestImpl.saveOne(tableLog);
		}
		
		return Result.ok(buffer.toString());
	}

	public Table getTableBySQL(String sql) {
		Assert.notEmpty(sql, "sql不能为空");

		Table table = new Table();
		List<Column> columns = new ArrayList<>();
		String tbl = sql.substring(sql.indexOf("CREATE TABLE `") + "CREATE TABLE `".length(), sql.indexOf("` ("));
		String startStr = "CREATE TABLE `"+tbl+"` (";
		int start = sql.indexOf(startStr);
		int end = sql.indexOf(") ENGINE="); //InnoDB
		String temp = sql.substring(end);
		if (temp.contains("COMMENT") && temp.contains("'")) {
			temp = temp.substring(temp.indexOf(" COMMENT='") + " COMMENT='".length());
			table.setCmmt(temp.contains("'") ? temp.substring(0, temp.indexOf("'")) : "");
		}
		table.setName(tbl);
		if (start >= 0 && end > start + startStr.length()) {
			List<Index> indexs = new ArrayList<>();
			List<String> arrIndex = new ArrayList<>();
			String newSql = sql.substring(start + startStr.length(), end);
			String[] arr = newSql.split(",\n");
			for (int i = 0; i < arr.length; i++) {
				String line = arr[i];
				if (line.startsWith("\n")) {
					line = line.replace("\n", "");
				}
				String oriLine = line;
				line = line.toUpperCase();
				// 字段
				if (line.startsWith("  `")) {
					Column column = new Column();
					column.setNotNull(false);
					column.setRequired(false);
					column.setUnsigned(false);

					if (line.contains(" COLLATE ")) {
						temp = line.substring(line.indexOf(" COLLATE ") + " COLLATE ".length());
						line = line.replace(" COLLATE " + temp.substring(0, temp.indexOf(" ")), "");
					}
					if (line.contains(" CHARACTER SET ")) {
						temp = line.substring(line.indexOf(" CHARACTER SET ") + " CHARACTER SET ".length());
						line = line.replace(" CHARACTER SET " + temp.substring(0, temp.indexOf(" ")), "");
					}
					if (line.contains("NOT NULL")) {
						column.setNotNull(true);
						column.setRequired(true);
						line = line.replace(" NOT NULL", "");
					}
					if (line.contains("UNSIGNED")) {
						column.setUnsigned(true);
						line = line.replace(" UNSIGNED", "");
					}

					if (line.contains(" COMMENT '")) {
						/*temp = line.substring(line.toUpperCase().indexOf(" COMMENT '") + " COMMENT '".length());
						column.setCmmt(temp.substring(0, temp.indexOf("'")));*/
						// 注释不能转换成大写
						temp = oriLine.substring(oriLine.toUpperCase().indexOf(" COMMENT '") + " COMMENT '".length());
						column.setCmmt(temp.substring(0, temp.indexOf("'")));
						line = line.substring(0, line.indexOf(" COMMENT '"));
						// 判断是否有注释
						if (!StrUtil.isEmpty(column.getCmmt())) {
							column.setCmmt(column.getCmmt().replace("（", "(").replace("）", ")"));
							if (column.getCmmt().contains("(") || column.getCmmt().contains(")")) {
								temp = column.getCmmt().replace("-", ":")
										.replace("：", ":").replace("=", ":")
										.replace("，", ",").replace("；", ",")
										.replace("、", ",");
								if (temp.contains("(") && temp.indexOf(")") > temp.indexOf("(") && temp.contains(":")) {
									column.setLimits(temp.substring(temp.indexOf("(") + 1, temp.indexOf(")")));
									column.setCmmt(temp.substring(0, temp.indexOf("(")));
								}
							}
						}
					}
					if (line.contains(" DEFAULT ")) {
						temp = line.substring(line.indexOf(" DEFAULT ") + " DEFAULT ".length());
						column.setDefVal(temp.contains(" ") ? temp.substring(0, temp.indexOf(" ")) : temp);
						column.setDefVal(column.getDefVal().replace("'", "").replace("CURRENT_TIMESTAMP", "NOW"));
						// line = line.replace(" DEFAULT " + column.getDefVal(), "");
						line = line.substring(0, line.indexOf(" DEFAULT "));
					}
					if (line.startsWith("  `")) {
						temp = line.substring(line.indexOf("  `") + "  `".length());
						column.setName(temp.substring(0, temp.indexOf("`")));
						line = line.replace("  `"+column.getName()+"` ", "");
						column.setName(column.getName().toLowerCase());
					}

					column.setLength(0);
					if (line.contains("(")) {
						//decimal(16,12)
						temp = line.substring(line.indexOf("(") + 1, line.length() - 1);
						if (temp.contains(",")) {
							//column.setDotLeft(Integer.valueOf(temp.substring(0, temp.indexOf(","))));
							column.setDotRight(Integer.valueOf(temp.substring(temp.indexOf(",") + 1)));
							column.setLength(Integer.valueOf(temp.substring(0, temp.indexOf(","))));
						} else {
							if (temp.indexOf(")") > 0) {
								temp = temp.substring(0, temp.indexOf(")"));
							}
							column.setLength(Integer.valueOf(temp));
						}

						temp = line.substring(0, line.indexOf("("));
					} else {
						temp = line;
						if (temp.contains(" ")) {
							temp = temp.substring(0, temp.indexOf(" "));
						}
					}
					column.setType(AutoUtil.getTypeBySql(temp, column.getLength()));
					column.setFormType(AutoUtil.getFormTypeBySql(column.getName(), temp, column.getLength()));
					column.setOrderNo(columns.size() + 1);
					if (column.getLength() <= 0 && column.getType() >= 3 && column.getType() <= 7) {
						column.setLength(8);
					}
					if (column.getType() == 2 && !StrUtil.isEmpty(column.getLimits())) {
						column.setCmmt(column.getCmmt() + "(" + column.getLimits() + ")");
						column.setLimits("");
					}
					if (!isSpecial(i, column.getName())) {
						column.setListShow(true);
						column.setFormShow(true);
					}
					columns.add(column);
				}
				// 索引
				else {
					// logger.debug("索引" + s);
					Index index = new Index();
					if (line.startsWith("  PRIMARY KEY")) {
						index.setType(1);
						index.setName("idx_prikey");
						index.setColumns("id");
					} else {
						index.setType(line.startsWith("  UNIQUE KEY") ? 2 : 1);
						temp = line.substring(line.indexOf("`") + "`".length());
						index.setName(temp.substring(0, temp.indexOf("`")).toLowerCase());
						temp = line.substring(line.indexOf("(") + "(".length());
						index.setColumns(temp.substring(0, temp.indexOf(")"))
								.replace("`", "").toLowerCase());
						for (String c : index.getColumns().split(",")) {
							if (!arrIndex.contains(c)) {
								arrIndex.add(c);
							}
						}
					}
					// logger.debug(index);
					indexs.add(index);
				}
			}
			for (Column column : columns) {
				if (arrIndex.contains(column.getName())) {
					column.setQueryType(1);
				}
				// logger.debug("column===>{}", column);
			}
			table.setColumnList(columns);
			table.setIndexList(indexs);
		}
		// 默认两栏
		table.setRowCol(0);
		table.setStatus(4);
		table.setIsExport(true);
		table.setIsImport(false);
		table.setGenFiles("vue");
		return table;
	}
}
